import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Like, Repository } from 'typeorm'
import { CategoryEntity } from './category.entity'
import { CreateCategoryDto, UpdateCategoryDto } from './dto/category.dto'

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly repo: Repository<CategoryEntity>,
  ) {}

  // 分页列表
  async page(query: any) {
    const pageNum = Number(query.pageNum || 1)
    const pageSize = Number(query.pageSize || 10)
    const where: any = {}
    if (query.name) where.name = Like(`%${query.name}%`)
    if (query.status !== undefined && query.status !== '') where.status = Number(query.status)
    if (query.parentId !== undefined && query.parentId !== '') where.parentId = Number(query.parentId)

    const [list, total] = await this.repo.findAndCount({
      where,
      order: { sort: 'ASC', categoryId: 'DESC' },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    })
    return { list, total }
  }

  // 详情
  async findOne(id: number) {
    return this.repo.findOne({ where: { categoryId: id } })
  }

  // 新增
  async create(dto: CreateCategoryDto) {
    const entity = this.repo.create(dto as any)
    return this.repo.save(entity)
  }

  // 更新
  async update(id: number, dto: UpdateCategoryDto) {
    await this.repo.update({ categoryId: id }, dto as any)
    return this.findOne(id)
  }

  // 删除（支持批量）
  async remove(ids: number[]) {
    if (!ids?.length) return
    await this.repo.delete(ids)
  }

  // 状态变更
  async changeStatus(categoryId: number, status: number) {
    await this.repo.update({ categoryId }, { status })
    return this.findOne(categoryId)
  }
}
